//package com.hanlink.dsp.ui;
//
//import android.Manifest;
//import android.content.Intent;
//import android.content.pm.PackageManager;
//import android.net.Uri;
//import android.os.Build;
//import android.os.Bundle;
//import android.util.SparseArray;
//import android.view.Gravity;
//import android.view.Menu;
//import android.view.MenuItem;
//import android.view.View;
//import android.view.WindowInsets;
//import android.view.WindowInsetsController;
//import android.widget.Button;
//import android.widget.ImageButton;
//import android.widget.RadioGroup;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import androidx.annotation.NonNull;
//import androidx.appcompat.app.ActionBarDrawerToggle;
//import androidx.appcompat.widget.Toolbar;
//import androidx.core.app.ActivityCompat;
//import androidx.core.content.ContextCompat;
//import androidx.core.view.GravityCompat;
//import androidx.drawerlayout.widget.DrawerLayout;
//import androidx.lifecycle.ViewModelProvider;
//import androidx.lifecycle.ViewModelProviders;
//
//import com.hanlink.dsp.DspSettings;
//import com.hanlink.dsp.R;
//import com.hanlink.dsp.ca.ui.fragment.AdvanceFragment;
//import com.hanlink.dsp.ca.ui.fragment.EqFragment;
//import com.hanlink.dsp.ca.ui.fragment.XoverFragment;
//import com.hanlink.dsp.ui.activities.HomeViewModel;
//import com.hanlink.dsp.ui.broadcast.UploadReceiver;
//import com.hanlink.dsp.ui.dialog.AskAlertDialog;
//import com.hanlink.dsp.ui.fragment.DeviceFragment;
//import com.hanlink.dsp.ui.fragment.SaveDrawerFragment;
//import com.hanlink.dsp.ui.fragment.Summing3Fragment;
//import com.hanlink.dsp.util.BLog;
//import com.hanlink.dsp.util.DataUtil;
//import com.inuker.bluetooth.library.Constants;
//import com.inuker.bluetooth.library.search.SearchResult;
//import com.qztech.bluetooth.BluetoothClientManager;
//import com.qztech.bluetooth.BluetoothConfig;
//import com.qztech.bluetooth.event.BleConnectFailedEvent;
//import com.qztech.bluetooth.event.BleConnectStatusEvent;
//import com.qztech.bluetooth.event.BluetoothStateEvent;
//import com.qztech.bluetooth.event.DeviceFoundedEvent;
//import com.qztech.bluetooth.event.SearchStateEvent;
//import com.qztech.sdk.ui.activities.BaseFragmentActivity;
//import com.qztech.sdk.ui.fragment.BaseDrawerFragment;
//import com.qztech.sdk.ui.fragment.BaseFragment;
//import com.qztech.sdk.ui.fragment.SaveFragmentCallback;
//
//import org.greenrobot.eventbus.Subscribe;
//import org.greenrobot.eventbus.ThreadMode;
//
//import java.util.ArrayList;
//import java.util.List;
//
//@SuppressWarnings("unused")
//public class CaDspActivity extends BaseFragmentActivity implements SaveFragmentCallback {
//    private UploadReceiver uploadReceiver;
//
//    //------Fragment------
//    private Class<? extends BaseFragment>[] mTargetFragments = new Class[]{
//            Summing3Fragment.class,
//            XoverFragment.class,
//            AdvanceFragment.class,
//            EqFragment.class
//    };
//    private SaveDrawerFragment mSaveDrawerFragment;
//    private DeviceFragment mBluetoothDrawerFragment;
//
//    //-----UI-----
//    private TextView mTitleText;
//    private Toolbar mToolbar;
//    private ImageButton mBtnBack;
//    private Button mBtnSave;
//    private RadioGroup mRdogTabs;
//    private DrawerLayout mDrawLayout;
//
//    //-------Var-------
//    private int mTabId = 0;
//    private String[] mResTitles;
//    private HomeViewModel mHomeViewModel;
//    private boolean mIsFoundDevice;
//    private boolean mIsAutoConnect = true;
//
//    @Override
//    protected int getResourceId() {
//        return R.layout.activity_ezdsp;
////        return R.layout.activity_main;
//    }
//
//    @Override
//    public boolean hasRegisterEventBus() {
//        return true;
//    }
//
//    @Override
//    protected void onCreate(final Bundle paramBundle) {
//        super.onCreate(paramBundle);
//        if (Build.VERSION.SDK_INT >= 21) {
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
////            |View.SYSTEM_UI_FLAG_FULLSCREEN
//            );
//            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
//        }
//
//        mHomeViewModel = ViewModelProviders.of(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(HomeViewModel.class);
//        mHomeViewModel.loadData();
//        subscribeToViewModel();
//        initView();
//        initFragment();
//        uploadReceiver = new UploadReceiver(this);
//        uploadReceiver.start();
//        openShareFile();
//    }
//
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setIntent(intent);
//        openShareFile();
//    }
//
//    private void openShareFile() {
//        Intent intent = getIntent();
//        String action = intent.getAction();
//        Uri uri = null;
//        if (Intent.ACTION_VIEW.equals(action)) {
//            uri = intent.getData();
//        } else if (Intent.ACTION_SEND.equals(action)) {
//            uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
//        }
//        if (uri != null) {
//            String path = Uri.decode(uri.getEncodedPath());
//            BLog.d("share", path + "");
//            mHomeViewModel.parseShareFile(uri);
//        }
//    }
//
//    private void initView() {
//        findViews();
//        initToolBar();
//        initDrawableLayout();
//        initListeners();
//        requestPermissions();
//    }
//
//    protected void initFragment() {
//        mResTitles = getResources().getStringArray(R.array.btdsp_tabs);
//        this.mFragmentSparseArray = new SparseArray<>();
//        int i = 0;
//        try {
//            while (i < this.mTargetFragments.length) {
//                BaseFragment localBaseFragment = this.mTargetFragments[i].newInstance();
//                this.mFragmentSparseArray.put(i, localBaseFragment);
//                i += 1;
//            }
//            this.mTabId = 0;
//            this.mCurrentFragment = this.mFragmentSparseArray.get(this.mTabId);
//            setTitle(this.mResTitles[this.mTabId]);
//            addFragment(this.mCurrentFragment);
//        } catch (Exception localException) {
//            localException.printStackTrace();
//        }
//    }
//
//    private void requestPermissions() {
//        List<String> permissions = new ArrayList<>();
//        String[] permissionArray = {
////                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.ACCESS_FINE_LOCATION,
////				Manifest.permission.READ_PHONE_STATE,
//        };
//        for (String p : permissionArray) {
//            if (ContextCompat.checkSelfPermission(this,
//                    p)
//                    != PackageManager.PERMISSION_GRANTED) {
//                permissions.add(p);
//            }
//        }
//        if (permissions.size() > 0) {
//            ActivityCompat.requestPermissions(this,
//                    permissions.toArray(new String[permissions.size()]),
//                    1);
//        } else {
//            initBluetooth();
//        }
//    }
//
//
//    private void findViews() {
//        mRdogTabs = findViewById(R.id.rg_tabs);
//        mDrawLayout = findViewById(R.id.drawer_layout);
//        mToolbar = findViewById(R.id.id_toolbar);
//        mTitleText = findViewById(R.id.txt_title);
//        mBtnSave = findViewById(R.id.btn_save);
//        mBtnBack = findViewById(R.id.btn_home);
//        mSaveDrawerFragment = ((SaveDrawerFragment) mFragmentManager.findFragmentById(R.id.drawer_save));
//        mBluetoothDrawerFragment = ((DeviceFragment) mFragmentManager.findFragmentById(R.id.drawer_bluetooth));
//    }
//
//    private void initDrawableLayout() {
//        mBluetoothDrawerFragment.setUp(R.id.drawer_bluetooth, mDrawLayout, null);
//        mSaveDrawerFragment.setUp(R.id.drawer_save, mDrawLayout, null);
//        mDrawLayout.setDrawerLockMode(1);
//        mDrawLayout.addDrawerListener(new ActionBarDrawerToggle(this, mDrawLayout, this.mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
//            public void onDrawerOpened(View drawerView) {
//                int gravity = ((DrawerLayout.LayoutParams) drawerView.getLayoutParams()).gravity;
//                if (gravity == GravityCompat.START) {
//                    mDrawLayout.closeDrawer(GravityCompat.END);
//                } else {
//                    mDrawLayout.closeDrawer(GravityCompat.START);
//                    mIsAutoConnect = false;
//                }
//                super.onDrawerOpened(drawerView);
//            }
//
//            @Override
//            public void onDrawerClosed(View drawerView) {
//                super.onDrawerClosed(drawerView);
//                int gravity = ((DrawerLayout.LayoutParams) drawerView.getLayoutParams()).gravity;
//                if (gravity == GravityCompat.END) {
//                    mIsAutoConnect = true;
//                }
//            }
//        });
//        this.mSaveDrawerFragment.setCallbacks(this);
//    }
//
//    private void initToolBar() {
//        setSupportActionBar(this.mToolbar);
//        if (getSupportActionBar() != null) {
//            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//            getSupportActionBar().setHomeButtonEnabled(false);
//            getSupportActionBar().setDisplayShowTitleEnabled(false);
//        }
//        mToolbar.setOnMenuItemClickListener(item -> {
//            if (item.getItemId() == R.id.action_settings) {
//                openBluetoothMenu();
//            } else if (item.getItemId() == R.id.action_share) {
//                if (!BluetoothClientManager.getInstance(getApplicationContext()).isConnect()) {
//                    Toast.makeText(this, R.string.bluetooth_error, Toast.LENGTH_SHORT).show();
//                    return false;
//                }
//                readData();
//            }
//            return false;
//        });
//
//    }
//
//    private void initListeners() {
//        mRdogTabs.setOnCheckedChangeListener(this.onTabCheckedChangeListener);
//        mBtnSave.setOnClickListener(v -> {
//            if (!mDrawLayout.isDrawerOpen(Gravity.LEFT)) {
//                mDrawLayout.openDrawer(Gravity.LEFT);
//            } else {
//                mDrawLayout.closeDrawer(Gravity.LEFT);
//            }
//        });
//        this.mBtnBack.setOnClickListener(view -> finish());
//    }
//
//    public void initBluetooth() {
//        if (mHomeViewModel.isBluetoothOpen()) {
//            mHomeViewModel.searchBluetooth();
//        } else {
//            mHomeViewModel.openBluetooth();
//        }
//    }
//
//    @Override
//    public boolean onCreateOptionsMenu(Menu paramMenu) {
//        getMenuInflater().inflate(R.menu.menu_main, paramMenu);
//        return true;
//    }
//
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        BLog.d("onRequestPermissionsResult", permissions.toString());
//        initBluetooth();
//    }
//
//    @Override
//    protected void onStop() {
//        uploadReceiver.pause();
//        super.onStop();
//    }
//
//    @Override
//    protected void onDestroy() {
//        uploadReceiver.stop();
//        DspSettings.USER_PROFILE = null;
//        super.onDestroy();
//    }
//
//    @Override
//    public void onDrawerItemAdded(int paramInt1, View paramView, int paramInt2, long paramLong) {
//        this.mCurrentFragment.onRefreshFragment(BaseFragment.CMD_ADDED);
//    }
//
//    @Override
//    public void onDrawerItemDeleted(int paramInt1, View paramView, int paramInt2, long paramLong) {
//        this.mCurrentFragment.onRefreshFragment(BaseFragment.CMD_DELETED);
//    }
//
//    @Override
//    public void onDrawerItemSelected(int paramInt1, View paramView, int paramInt2, long paramLong) {
//        this.mSaveDrawerFragment.openOrCloseDrawer(paramInt1);
//        try {
//            DataUtil.loadData();
//            this.mCurrentFragment.onRefreshFragment(BaseFragment.CMD_SELECTED);
//            if (!BluetoothClientManager.getInstance(this).isConnect()) {
//                Toast.makeText(this, R.string.bluetooth_error, Toast.LENGTH_SHORT).show();
//                return;
//            }
//            mHomeViewModel.startUpload();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public void openBluetoothMenu() {
//        this.mBluetoothDrawerFragment.openOrCloseDrawer(Gravity.END);
//    }
//
//    private RadioGroup.OnCheckedChangeListener onTabCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
//        @Override
//        public void onCheckedChanged(RadioGroup group, int checkedId) {
//            Object tag = group.findViewById(checkedId).getTag();
//            int tabId = tag != null ? Integer.parseInt(String.valueOf(tag)) : 0;
//            mCurrentFragment = mFragmentSparseArray.get(tabId);
//            if (tabId == 0) {
//                mBluetoothDrawerFragment.disableDrawer(false, Gravity.END);
//            } else {
//                mBluetoothDrawerFragment.disableDrawer(true, Gravity.END);
//            }
//            if (mTabId != tabId) {
//                setTitle(mResTitles[tabId]);
//                replaceFragment(mCurrentFragment, tabId > mTabId);
//                DspSettings.CURRENT_TAB = mTabId = tabId;
//                mSaveDrawerFragment.reloadSettings();
//            }
//        }
//    };
//
//    private void setTitle(String paramString) {
//        if (this.mTitleText != null) {
//            this.mTitleText.setText(paramString);
//        }
//    }
//
//    private void subscribeToViewModel() {
//        mHomeViewModel.mParseLiveData.observe(this, resource -> {
//            if (resource != null && resource.isLoading()) {
//                showLoadingDialog("Load...", false);
//            } else if (resource != null && resource.isSuccess()) {
//                mCurrentFragment.onRefreshFragment(BaseFragment.CMD_SELECTED);
//                if (resource.data()) {
//                    dismissLoading();
////                    Toast.makeText(this, R.string.read_success, Toast.LENGTH_SHORT).show();
//                }
//            } else if (resource != null && resource.isError()) {
//                Toast.makeText(this, R.string.read_fail, Toast.LENGTH_SHORT).show();
//                dismissLoading();
//            }
//        });
//    }
//
//    @Override
//    public void readData() {
//
//        AskAlertDialog askAlertDialog = new AskAlertDialog(this, getString(R.string.read_data_message), false, dialog -> {
//            dialog.dismiss();
//            if (!BluetoothClientManager.getInstance(this).isConnect()) {
//                Toast.makeText(this, R.string.bluetooth_error, Toast.LENGTH_SHORT).show();
//                return;
//            }
//            mHomeViewModel.readData();
//        });
//        askAlertDialog.show();
//    }
//
//    //-----BluetoothEvent---------------
//
//    /**
//     * 蓝牙设备连接状态变化
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onBluetoothStateChanged(BleConnectStatusEvent event) {
//        switch (event.getStatus()) {
//            case Constants.STATUS_DISCONNECTED:
//                onDisconnected();
//                break;
//            case Constants.STATUS_CONNECTED:
//                onConnected(event.getDevice().getMac());
//                break;
//        }
//    }
//
//    /**
//     * 连接失败
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onConnectFailed(BleConnectFailedEvent event) {
//        showFail(getString(R.string.bluetooth_connect_fail));
//    }
//
//    /**
//     * 发现设备
//     */
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onFoundDevice(DeviceFoundedEvent event) {
//        SearchResult searchResult = event.getDevice();
//        if (!mIsFoundDevice && mIsAutoConnect && event.getDevice().getName().startsWith(BluetoothConfig.getName())) {
//
////            connect(searchResult.getAddress(), searchResult.getName());
//        }
//    }
//
//    public void connect(String mac, String name) {
//        mIsFoundDevice = true;
//        mHomeViewModel.cancelSearch();
//        showLoadingDialog(getString(R.string.bluetooth_to_connect), false);
//        mHomeViewModel.connect(mac, name);
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onBluetoothStateChanged(BluetoothStateEvent event) {
//        if (!event.isOpenOrClosed()) {
//            mHomeViewModel.cancelSearch();
//            Toast.makeText(this, R.string.bluetooth_closed, Toast.LENGTH_SHORT).show();
//        } else {
//            mHomeViewModel.searchBluetooth();
//        }
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onSearchEvent(SearchStateEvent event) {
//        if (!mIsAutoConnect) {
//            return;
//        }
//        switch (event.getStatus()) {
//            case SearchStateEvent.SEARCH_START:
//                if (mIsAutoConnect) {
//                    mIsFoundDevice = false;
//                }
////                showLoadingDialog(getString(R.string.bluetooth_search_device), false);
//                break;
//            case SearchStateEvent.SEARCH_STOP:
//                if (!mIsFoundDevice) {
////                    showFail(getString(R.string.bluetooth_discover_fail));
//                }
//                break;
//            case SearchStateEvent.SEARCH_CANCEL:
//                break;
//        }
//    }
//
//    private void onConnected(String mac) {
//        showSuccess(getResources().getString(R.string.bluetooth_connect_successful));
//        invalidateOptionsMenu();
//    }
//
//    private void onDisconnected() {
//        mHomeViewModel.cancelReadData();
//        showFail(getResources().getString(R.string.bluetooth_disconnect));
//        invalidateOptionsMenu();
//    }
//
//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        MenuItem menuItem = menu.findItem(R.id.action_settings);
//        if (menuItem != null) {
//            menuItem.setIcon(BluetoothClientManager.getInstance(getApplicationContext()).isConnect() ? R.drawable.ic_settings_checked : R.drawable.ic_settings);
//        }
//        return super.onPrepareOptionsMenu(menu);
//    }
//
//    public void resetAppAsk() {
//        AskAlertDialog askAlertDialog = new AskAlertDialog(this, getString(R.string.read_data_ask_sure), false, dialog -> {
//            dialog.dismiss();
//            resetApp();
//        });
//        askAlertDialog.show();
//    }
//
//    private void resetApp() {
//        mHomeViewModel.resetApp();
//        mDrawLayout.closeDrawer(Gravity.END);
//        mCurrentFragment.onRefreshFragment(BaseFragment.CMD_SELECTED);
//        DspSettings.reset = false;
//    }
//
//}
